/*
 * Copyright (C) 2014 luke.
 * 
 * This file is part of Silvie.
 * 
 * Silvie is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Silvie is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Silvie.  If not, see <http://www.gnu.org/licenses/>.
 */

package silvie.resources;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.file.Files;

import silvie.gui.Preview;
import silvie.gui.previewers.AbstractPreviewer;

/**
 * Abstract Silver resource. It can be an image, a sprite container, a 3D model
 * or a video.
 * 
 * @author luke
 */
public abstract class AbstractResource {
	protected File resource;
	protected boolean openAsStream;
	protected RandomAccessFile stream;
	protected byte[] resourceBytes;

	/**
	 * AbstractResource constructor.
	 * 
	 * @param resource the resource file.
	 * @param openAsStream true if the file should be read directly as a
	 *        RandomAccessFile instead of being cached.
	 */
	public AbstractResource(File resource, boolean openAsStream) {
		this.resource = resource;
		this.openAsStream = openAsStream;
		this.stream = null;
		this.resourceBytes = null;
	}

	/**
	 * Closes the RandomAccessFile if this resource was created with
	 * {@code openAsStream = true}.
	 * 
	 * @throws IOException if a file error occurs.
	 */
	protected void closeStream() throws IOException {
		if (this.openAsStream && this.stream != null && this.stream.getFD().valid()) {
			this.stream.close();
		}
	}

	/**
	 * Reads the resource's bytes, performs unpacking if necessary and extracts
	 * the relevant information.
	 * 
	 * <p>
	 * This method must be overridden and {@code super.extract()} must be
	 * called.
	 * 
	 * @throws Exception if an extraction error occurs.
	 */
	public void extract() throws Exception {
		if (!this.openAsStream) {
			this.resourceBytes = Files.readAllBytes(this.resource.toPath());
		} else {
			this.stream = new RandomAccessFile(this.resource, "r");
		}
	}

	/**
	 * Returns the appropriate Previewer for this resource.
	 * 
	 * @param preview the Preview to display on.
	 * @return a Previewer for this resource.
	 */
	public abstract AbstractPreviewer getPreviewer(Preview preview);
}
